﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using RBAC.Web.Mapper;
using RBAC.Web.Models;
using RBAC.Web.Service;
using RBAC.Web.Utilities;

namespace RBAC.Web.Controllers
{
    public class RoleUserController : Controller
    {
        ////*****  Begin For Paging  *****//
        //int total;
        //int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"]);
        ////*****  End For Paging  *****//

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult ListRoleUser(int? page, string sort = "", string sortdir = "asc"
                            , int IdSearch = 0
                        )
        {
            //ถ้าตัวมันเป็นลูกของตัวอื่น ต้องทำการ clear ค่า TempData ของแม่ก่อน

            // end clear ค่า TempData

            ListRoleUserModel model = new ListRoleUserModel();
            /*GetAllResponseModel<RoleUserModel> temp = Search(new GetAllRoleUserRequestModel()
            {
									 Id = IdSearch,
						                    Sort = sort,
					SortType = sortdir == "asc" ? sType.ASC : sType.DESC
            });
            model.ListItems = temp.List;*/

            return View(model);
        }

        [HttpPost]
        public ActionResult ListRoleUser(string submitButton, string[] checkbox, ListRoleUserModel input
        )
        {
            ////*****  Begin For Paging  *****//
            ListRoleUserModel model = new ListRoleUserModel();
            //{
            //                                                                IdSearch = input.IdSearch,
            //                                Sort = input.Sort,
            //    SortType = submitButton == "Search" ? sType.ASC : input.SortType,
            //    CurrentPage = input.CurrentPage == 0 || submitButton == "Search" ? 1 : input.CurrentPage,
            //    ItemsPerPage = input.ItemsPerPage == pageSize || input.ItemsPerPage == 0 ? pageSize : input.ItemsPerPage,                
            //};
            ////*****  End For Paging  *****//
            if (ModelState.IsValid)
            {
                model.ListItems = PrepareSearch(model);
                ////*****  Begin For Paging  *****//
                //model.TotalItems = total;
                ////*****  End For Paging  *****//
            }
            return View(model);
        }

        public ActionResult EditRoleUser(String Id)
        {
            ServiceClient service = new ServiceClient();

            GetAllRoleUserRequestDto objGet = new GetAllRoleUserRequestDto()
            {
                EqPk = true,
                Id = StringParser.GetValue<int>(Id)
            };

            var list = service.GetAllRoleUser(objGet);
            RoleUserModel resultModel = null;


            if (list.Data != null && list.Data.Count > 0)
            {
                RoleUserDto resultDto = list.Data[0];
                resultModel = RoleUserMapper.DtoToModel(resultDto);

                //Get One-to-many data data ของลูก
                // สร้าง method PrepareXXXSearch
            }


            // Start add for summary field   
            // ถ้ามีฟิลด์ Summary และต้องบันทึกลง Database ด้วย ก็ต้องใส่ค่าให้ฟิลด์ดังกล่าวด้วย

            // End add for summary field

            SetupRegisterViewModel(resultModel);
            return View(resultModel);
        }

        [HttpPost]
        public ActionResult Update(RoleUserModel inputModel, String Id)
        {
            ImageClass IClass = new ImageClass();
            if (ModelState.IsValid)
            {
                ServiceClient service = new ServiceClient();
                var output = service.UpdateRoleUser(RoleUserMapper.ModelToDto(inputModel));
                var listDisplay = PrepareRetrunFromOperation(new ListRoleUserModel(), output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Edit, output.Status));


                // เพิ่ม message แสดงในหน้าแม่
                TempData["RoleUserMessage"] = listDisplay.Message;
                TempData["RoleUserStatus"] = output.Status;
                if (output.Data != null)
                {
                    TempData["RoleUserId"] = output.Data.Id;
                }
                return View("ListRoleUser", listDisplay);
            }
            else
            {
                //Get One-to-many data data ของลูก
                // สร้าง method PrepareXXXSearch
                SetupRegisterViewModel(inputModel);
                return View("EditRoleUser", inputModel);
            }
        }

        public ActionResult Add()
        {
            RoleUserModel model = new RoleUserModel();
            SetupRegisterViewModel(model);


            return View("AddRoleUser", model);
        }

        [HttpPost]
        public ActionResult AddRoleUser(RoleUserModel inputModel)
        {
            ImageClass IClass = new ImageClass();
            if (ModelState.IsValid)
            {
                ServiceClient service = new ServiceClient();
                var output = service.AddRoleUser(RoleUserMapper.ModelToDto(inputModel));
                var listDisplay = PrepareRetrunFromOperation(new ListRoleUserModel(), output.Data, output.Status,
                                  Utilities.MessageUtil.GetMessage(Operation.Add, output.Status));


                // เพิ่ม message แสดงในหน้าแม่
                TempData["RoleUserMessage"] = listDisplay.Message;
                TempData["RoleUserStatus"] = output.Status;
                if (output.Data != null)
                {
                    TempData["RoleUserId"] = output.Data.Id;
                }
                return View("ListRoleUser", listDisplay);
            }
            else
            {
                SetupRegisterViewModel(inputModel);
                return View(inputModel);
            }
        }

        [HttpPost]
        public string DeleteRoleUsers(string[] RoleUserCheckbox)
        {
            ListRoleUserModel input = new ListRoleUserModel();
            if (ModelState.IsValid)
            {
                input = Delete(RoleUserCheckbox, input);
            }

            if (input.IsSuccessed.GetValueOrDefault(false))
                return Boolean.TrueString;
            else
                return Boolean.FalseString;
        }

        [HttpPost]
        public String DeleteRoleUserById(string Id)
        {
            List<string> delList = new List<string>();
            delList.Add(Id);
            ServiceClient service = new ServiceClient();
            var output = service.DeleteRoleUser(delList);

            if (output.Status)
            {
                foreach (string delListID in delList)
                {
                    if (System.IO.Directory.Exists(Server.MapPath("~/Image/RoleUser") + "\\" + delListID + "\\"))
                    {
                        System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(Server.MapPath("~/Image/RoleUser") + "\\" + delListID + "\\"); DI.Delete(true);
                    }
                }
            }

            //แสดง message ให้ class แม่
            TempData["RoleUserMessage"] = Utilities.MessageUtil.GetMessage(Operation.Delete, output.Status);
            TempData["RoleUserStatus"] = output.Status;

            if (output.Status)
                return Boolean.TrueString;
            else
                return Boolean.FalseString;

        }

        // Check does Id exist
        [HttpPost]
        public JsonResult doesIdExist(string Id, string Mode, string OldValue)
        {
            bool callCheck = false;
            if (Mode.Equals("Add", StringComparison.OrdinalIgnoreCase))
            {
                callCheck = true;
            }
            else if (Mode.Equals("Edit", StringComparison.OrdinalIgnoreCase))
            {
                if (!OldValue.Trim().Equals(Id.Trim(), StringComparison.OrdinalIgnoreCase))
                    callCheck = true;
            }

            if (callCheck)
            {
                var service = new ServiceClient();
                var exist = service.ExistRoleUser(Id).Data;
                return Json(!exist);
            }
            else
                return Json(true);
        }

        #region private methods

        private ListRoleUserModel Delete(string[] inputList, ListRoleUserModel input)
        {
            List<string> delList = new List<string>();
            var listDisplay = new ListRoleUserModel();
            if (inputList != null && inputList.Length > 0)
            {
                foreach (string id in inputList)
                {
                    delList.Add(id);
                }
                ServiceClient service = new ServiceClient();
                var output = service.DeleteRoleUser(delList);
                listDisplay = PrepareRetrunFromOperation(input, output.Data, output.Status,
                        Utilities.MessageUtil.GetMessage(Operation.Delete, output.Status));

                if (output.Status)
                {
                    foreach (string inputListSplit in inputList)
                    {
                        if (System.IO.Directory.Exists(Server.MapPath("~/Image/RoleUser") + "\\" + inputListSplit + "\\"))
                        {
                            System.IO.DirectoryInfo DI = new System.IO.DirectoryInfo(Server.MapPath("~/Image/RoleUser") + "\\" + inputListSplit + "\\"); DI.Delete(true);
                        }
                    }
                }

                TempData["RoleUserMessage"] = listDisplay.Message;
                TempData["RoleUserStatus"] = output.Status;
            }

            listDisplay.ListItems = PrepareSearch(listDisplay);
            return listDisplay;
        }

        private List<RoleUserModel> PrepareSearch(ListRoleUserModel input)
        {

            GetAllRoleUserRequestModel searchInputs = new GetAllRoleUserRequestModel()
            {
                Id = (input.IdSearch == null) ? 0 : input.IdSearch,

                Sort = input.Sort,
                SortType = input.SortType,

                ////*****  Begin For Paging  *****//
                //PagingInfo = new PagingInfoModel()
                //{
                //    CurrentPage = input.CurrentPage,
                //    ItemsPerPage = input.ItemsPerPage
                //}
                ////*****  End For Paging  *****//
            };
            var result = Search(searchInputs);

            ////*****  Begin For Paging  *****// 
            //total = result.PagingInfo.TotalItems;
            ////*****  End For Paging  *****//

            return result.List;
        }

        private GetAllResponseModel<RoleUserModel> Search(GetAllRoleUserRequestModel input)
        {
            ServiceClient service = new ServiceClient();
            GetAllRoleUserRequestDto gAllreq = new GetAllRoleUserRequestDto
            {
                Id = input.Id,
                SortType = input.SortType.ToString(),
                Sort = input.Sort,
                //*****  Begin For Paging  *****//
                // CurrentPage = input.PagingInfo.CurrentPage,
                // ItemsPerPage = input.PagingInfo.ItemsPerPage
                //*****  End For Paging  *****//

            };
            var response = service.GetAllRoleUser(gAllreq);
            var result = new GetAllResponseModel<RoleUserModel>();
            result.List = new List<RoleUserModel>();
            if (response != null)
            {
                if (response.Data != null && response.Data.Count > 0)
                {
                    foreach (RoleUserDto responseDTO in response.Data)
                    {
                        RoleUserModel resultModel = null;
                        RoleUserDto tempDto = responseDTO;
                        resultModel = RoleUserMapper.DtoToModel(tempDto);
                        // Start add for summary field

                        // End add for summary field



                        result.List.Add(resultModel);
                    }
                }
            }
            ////*****  Begin For Paging  *****//
            //result.PagingInfo = new PagingInfoModel()
            //{
            //    CurrentPage = gAllreq.CurrentPage,
            //    ItemsPerPage = gAllreq.ItemsPerPage,
            //    TotalItems = response.TotalItems
            //};
            //*****  End For Paging  *****//
            return result;
        }

        private ListRoleUserModel PrepareRetrunFromOperation(ListRoleUserModel listModel, RoleUserDto dto, bool status, string message)
        {
            if (status)
            {
                if (dto != null)
                {
                    listModel.ListItems.Add(RoleUserMapper.DtoToModel(dto));
                }
            }
            listModel.Message = message;
            listModel.IsSuccessed = status;
            return listModel;

        }




        private void SetupRegisterViewModel(RoleUserModel model)
        {
            //เช็คว่ามี Attribute ที่เป็น DateTime ใน model หรือเปล่าถ้ามี + ปีไป 543 ถ้าปีเป็น ค.ศ.
            Utilities.Utilities.PrepareDateTimeProperity(model);
        }

        /// <summary>
        /// Name ::: Mr. Akawit Tangkupatanonth
        /// Date ::: 16/03/2014
        /// Description ::: This function for call validate method in validate class
        /// </summary>
        /// <returns>Boolean</returns>

        #endregion


    }
}
